package sendsms

import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	"github.com/alibabacloud-go/tea/tea"
	"gopkg.in/yaml.v2"
	"log"
	"os"
)

var (
	logger = log.Default()
)

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func createClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

/**
 * 请求阿里云发送短信
 */
func send(data map[string]string) (_result *dysmsapi20170525.SendSmsResponse, _err error) {
	client, _err := createClient(tea.String(data["accessKey"]), tea.String(data["accessSecret"]))
	if _err != nil {
		return nil, _err
	}
	codeJson := fmt.Sprintf("{\"code\": \"%s\"}", data["code"])

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String(data["signName"]),
		TemplateCode:  tea.String(data["templateCode"]),
		PhoneNumbers:  tea.String(data["phoneNum"]),
		TemplateParam: tea.String(codeJson),
	}
	// 复制代码运行请自行打印 API 的返回值
	_result, _err = client.SendSms(sendSmsRequest)
	if _err != nil {
		return nil, _err
	}
	return _result, _err
}

type SmsConfig struct {
	AccessKeyId     string `yaml:"accessKeyId"`
	AccessKeySecret string `yaml:"accessKeySecret"`
	SignName        string `yaml:"signName"`
	TemplateCode    string `yaml:"templateCode"`
	Endpoint        string `yaml:"endpoint"`
}
type SMSYamlConfig struct {
	Config SmsConfig `yaml:"SmsConfig"`
}

func Init(configFilepath string) (*SMSYamlConfig, error) {
	var config SMSYamlConfig
	file, err := os.ReadFile(configFilepath)
	if err != nil {
		logger.Println(err)
		return nil, err
	}
	err = yaml.Unmarshal(file, &config)
	if err != nil {
		logger.Println(err)
		return nil, err
	}
	logger.Println("sms配置文件读取成功！", config)
	return &config, nil
}

func SendCodeToPhone(smsConfig *SMSYamlConfig, phone, code string) (*dysmsapi20170525.SendSmsResponse, error) {
	config := *smsConfig
	var data = map[string]string{
		"accessKey":    config.Config.AccessKeyId,
		"accessSecret": config.Config.AccessKeySecret,
		"signName":     config.Config.SignName,
		"templateCode": config.Config.TemplateCode,
		"phoneNum":     phone,
		"code":         code,
	}
	result, err := send(data)
	if err != nil {
		logger.Println(err)
		return nil, err
	}
	logger.Println("短信发送成功！")
	return result, nil
}
